#include "command_connection.hpp"

namespace lge2d
{
namespace lan
{

//------------------------------------------------------------------------------
CommandConnection::CommandConnection()
{

}

//------------------------------------------------------------------------------
CommandConnection::~CommandConnection()
{
	m_connection.Disconnect();

	HandlersMap_t::iterator it = m_handlers.begin(),
							it_end = m_handlers.end();
	for(; it != it_end; ++it)
	{
		delete it->second;
	}
	m_handlers.clear();
}

//------------------------------------------------------------------------------
// подключение к серверу
Connection::ErrorCode CommandConnection::Connect(const std::string& host,
		unsigned short port /* = DEFAULT_SERVER_PORT */,
		float timeOut /* = CLIENT_CONNECTIONG_TIMEOUT */)
{
	return m_connection.Connect(host, port, timeOut);
}

//------------------------------------------------------------------------------
// разрыв соединения
void CommandConnection::Disconnect()
{
	m_connection.Disconnect();
}

Connection::ErrorCode CommandConnection::GetLastError() const
{
	return m_connection.GetLastError();
}

//------------------------------------------------------------------------------
const Connection::Statictics& CommandConnection::GetStatistics() const
{
	return m_connection.GetStatistics();
}
//------------------------------------------------------------------------------
bool CommandConnection::IsConnected() const
{
	return m_connection.GetState() == Connection::Connected;
}

//------------------------------------------------------------------------------
bool CommandConnection::Update(float dt)
{
	bool res = m_connection.Update(dt);

	size_t receivedCoount = m_connection.GetReceivedCount();
	if (receivedCoount)
	{
		for (size_t idx = 0; idx < receivedCoount; ++idx)
		{
			Packet packet = m_connection.Get(idx);
			OnPacket(packet);
		}

		m_connection.ClearReceived();
	}

	return res;
}

} /* namespace lan */
} /* namespace lge2d */
